import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable, UnauthorizedException } from '@nestjs/common'
import { ConfigService } from '@nestjs/config'
import { ConfigEnum } from '../enum/config.enum'
// JwtStrategy的作用：验证从客户端发来的 JWT 令牌，如果合法，允许访问保护的资源。
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(protected ConfigService: ConfigService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: true, //true：手动控制过期校验 false：禁用忽略过期，passport-jwt 会自动处理过期
      secretOrKey: ConfigService.get<string>(ConfigEnum.SECRET) || 'default_secret_key' //密钥
    })
  }

  validate(payload: { sub: number; username: string; exp: number }) {
    const currentTime = Math.floor(Date.now() / 1000) //向下取整
    if (currentTime > payload.exp) {
      throw new UnauthorizedException('Token 已过期，请重新登录')
    }
    // req.user
    return { userId: payload.sub, username: payload.username }
  }
}
